<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus, Delete } from '@element-plus/icons-vue'
import { getTags } from '../api/tag'
import { createArticle, uploadImage } from '../api/article'
import VMdEditor from '@kangc/v-md-editor'
import '@kangc/v-md-editor/lib/style/base-editor.css'
import vuepressTheme from '@kangc/v-md-editor/lib/theme/vuepress.js'
import '@kangc/v-md-editor/lib/theme/style/vuepress.css'
import Prism from 'prismjs'

// 配置 Markdown 编辑器
VMdEditor.use(vuepressTheme, {
  Prism
})

const router = useRouter()
const saving = ref(false)
const tags = ref([])

// 文章数据
const article = ref({
    title: '',
    content: '',
    description: '',
    tags: [],
    coverImage: ''
})

const rules = {
    title: [
        { required: true, message: '请输入文章标题', trigger: 'blur' },
        { min: 2, max: 100, message: '标题长度在 2 到 100 个字符', trigger: 'blur' }
    ],
    content: [
        { required: true, message: '请输入文章内容', trigger: 'blur' }
    ]
}

const formRef = ref(null)

// 加载标签列表
const loadTags = async () => {
    try {
        const res = await getTags()
        if (res.code === 200) {
            tags.value = res.data
        }
    } catch (error) {
        console.error('Failed to load tags:', error)
    }
}

// 上传封面图前的验证
const beforeCoverUpload = (file) => {
    const isImage = file.type.startsWith('image/')
    const isLt2M = file.size / 1024 / 1024 < 2

    if (!isImage) {
        ElMessage.error('只能上传图片文件!')
        return false
    }
    if (!isLt2M) {
        ElMessage.error('图片大小不能超过 2MB!')
        return false
    }
    return true
}

// 上传封面图
const uploadCover = async ({ file }) => {
    try {
        const formData = new FormData()
        formData.append('file', file)
        const res = await uploadImage(formData)
        if (res.code === 200) {
            article.value.coverImage = res.data
            ElMessage.success('封面图上传成功')
        }
    } catch (error) {
        ElMessage.error('封面图上传失败')
    }
}

// 移除封面图
const removeCover = () => {
    article.value.coverImage = ''
}

// 保存文章
const handleSave = async () => {
    if (!article.value.title.trim()) {
        ElMessage.warning('请输入文章标题')
        return
    }
    if (!article.value.content.trim()) {
        ElMessage.warning('请输入文章内容')
        return
    }

    try {
        saving.value = true
        const res = await createArticle(article.value)
        if (res.code === 200) {
            ElMessage.success('文章发布成功')
            router.push(`/article/${res.data}`)
        }
    } catch (error) {
        ElMessage.error('文章发布失败')
    } finally {
        saving.value = false
    }
}

onMounted(() => {
    loadTags()
})
</script>

<template>
    <div class="write-container">
        <!-- 文章标题 -->
        <div class="title-section">
            <el-input
                v-model="article.title"
                placeholder="请输入文章标题..."
                class="title-input"
                :maxlength="100"
                show-word-limit
            />
        </div>

        <!-- 文章描述 -->
        <div class="description-section">
            <el-input
                v-model="article.description"
                type="textarea"
                :rows="3"
                placeholder="请输入文章描述(选填)..."
                :maxlength="200"
                show-word-limit
                resize="none"
            />
        </div>

        <!-- Markdown编辑器 -->
        <div class="editor-section">
            <v-md-editor
                v-model="article.content"
                height="calc(100vh - 480px)"
                @save="handleSave"
            />
        </div>

        <!-- 文章信息 -->
        <div class="article-info">
            <!-- 标签选择 -->
            <div class="info-section">
                <div class="section-title">文章标签</div>
                <el-select
                    v-model="article.tags"
                    multiple
                    filterable
                    allow-create
                    default-first-option
                    placeholder="选择或创建标签(最多3个)"
                    class="tag-select"
                    :multiple-limit="3"
                >
                    <el-option
                        v-for="tag in tags"
                        :key="tag.id"
                        :label="tag.name"
                        :value="tag.id"
                    />
                </el-select>
            </div>

            <!-- 封面图上传 -->
            <div class="info-section">
                <div class="section-title">封面图</div>
                <el-upload
                    class="upload-component"
                    :show-file-list="false"
                    :before-upload="beforeCoverUpload"
                    :http-request="uploadCover"
                >
                    <div class="upload-area" v-if="!article.coverImage">
                        <el-icon><Plus /></el-icon>
                        <span>添加封面图</span>
                    </div>
                    <div class="preview" v-else>
                        <img :src="article.coverImage" alt="封面图">
                        <div class="actions">
                            <el-button type="danger" icon="Delete" circle @click.stop="removeCover" />
                        </div>
                    </div>
                </el-upload>
            </div>
        </div>

        <!-- 操作按钮 -->
        <div class="actions">
            <div class="left-actions">
                <el-button @click="router.back()">取消</el-button>
                <el-button type="primary" @click="handleSave" :loading="saving">
                    发布文章
                </el-button>
            </div>
        </div>
    </div>
</template>

<style lang="scss" scoped>
// 定义变量
$primary-color: #3eaf7c;  // 主题色
$border-color: #dcdfe6;   // 边框色
$text-color: #2c3e50;     // 文字色

.write-container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;

    .title-section {
        margin-bottom: 20px;

        .title-input {
            font-size: 24px;
            
            :deep(.el-input__wrapper) {
                padding: 12px 20px;
                box-shadow: none;
                border: none;
                background: transparent;
            }
            
            :deep(.el-input__inner) {
                font-size: 24px;
                font-weight: 600;
                
                &::placeholder {
                    color: #999;
                }
            }
        }
    }

    .description-section {
        margin-bottom: 20px;

        :deep(.el-textarea__inner) {
            padding: 12px 16px;
            font-size: 15px;
            line-height: 1.6;
            
            &::placeholder {
                color: #999;
            }
        }
    }

    .article-info {
        display: flex;
        flex-direction: column;
        gap: 20px;
        margin-bottom: 20px;

        .info-section {
            .section-title {
                font-size: 15px;
                font-weight: 500;
                color: #606266;
                margin-bottom: 12px;
            }

            .tag-select {
                width: 100%;
            }

            .upload-component {
                .upload-area {
                    width: 200px;
                    height: 150px;
                    border: 2px dashed $border-color;
                    border-radius: 8px;
                    display: flex;
                    flex-direction: column;
                    justify-content: center;
                    align-items: center;
                    cursor: pointer;
                    transition: all 0.3s;
                    
                    &:hover {
                        border-color: $primary-color;
                        color: $primary-color;
                    }
                    
                    .el-icon {
                        font-size: 24px;
                        margin-bottom: 8px;
                    }
                }
                
                .preview {
                    width: 200px;
                    height: 150px;
                    border-radius: 8px;
                    overflow: hidden;
                    position: relative;
                    border: 2px dashed $border-color;
                    
                    img {
                        width: 100%;
                        height: 100%;
                        object-fit: cover;
                    }
                    
                    .actions {
                        position: absolute;
                        top: 50%;
                        left: 50%;
                        transform: translate(-50%, -50%);
                        opacity: 0;
                        transition: opacity 0.3s;
                        background: rgba(0, 0, 0, 0.5);
                        padding: 8px;
                        border-radius: 4px;
                        
                        &:hover {
                            opacity: 1;
                        }
                    }
                    
                    &:hover .actions {
                        opacity: 1;
                    }
                }
            }
        }
    }

    .editor-section {
        border: 1px solid $border-color;
        border-radius: 8px;
        overflow: hidden;
        margin-bottom: 20px;
    }

    .actions {
        display: flex;
        margin-top: 20px;

        .left-actions {
            display: flex;
            gap: 12px;
        }
    }
}
</style> 